//
//  RegisterYunPlaVC.m
//  reSearchDemo
//
//  Created by 云库 on 15/7/24.
//  Copyright (c) 2015年 Kiwaro. All rights reserved.
//

#import "RegisterYunPlaVC.h"
#import "KAlertView.h"
#import "YunPlatformSet.h"
#import "BSClient.h"
#import "HTTPGlobals.h"
@interface RegisterYunPlaVC ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
{
    UITableView *_tableView;
    
}
@end

@implementation RegisterYunPlaVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor=[UIColor whiteColor];
    [self setRightBarButtonImage:LOADIMAGE(@"btn_more") highlightedImage:nil selector:@selector(menu)];
    
    UIView * actionbar=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, 44)];
    self.navigationItem.titleView = actionbar;
    UILabel * lab=[[UILabel alloc]initWithFrame:CGRectMake(8, 0, 100, 40)];
    lab.text=@"注册云平台";
    lab.font=[UIFont systemFontOfSize:20];
    lab.textColor=[UIColor whiteColor];
    [actionbar addSubview:lab];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame)) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:_tableView];
    
    [self buildMainView];
}


-(UIView *)buildMainView{
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame))];
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 20, CGRectGetWidth(self.view.frame) - 40, 200)];
    textView.backgroundColor = [UIColor lightGrayColor];
    textView.editable = NO; //禁止编辑
    textView.autoresizingMask = UIViewAutoresizingFlexibleHeight;//自适应高度
    [headView addSubview:textView];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(CGRectGetMinX(textView.frame) + 20, CGRectGetMaxY(textView.frame)+ 10, 20, 20);
    btn.selected = NO;
    [btn setImage:[UIImage imageNamed:@"btn_radio_n@2x"] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"btn_radio_s@2x"] forState:UIControlStateSelected];
    [btn addTarget:self action:@selector(selectBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:btn];
    
    UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(btn.frame) + 10, CGRectGetMinY(btn.frame) + 2, 200, 20)];
    textLabel.text = @"同意云库云平台使用协议";
    textLabel.font = [UIFont systemFontOfSize:13];
    textLabel.textColor = [UIColor blackColor];
    [headView addSubview:textLabel];
    
    NSArray *titleArr = @[@"账       号:",@"名       称:",@"输入邮箱:",];
    NSArray *placeholderArr = @[@"账号3-10位的字母下划线和数字组成",@"6-18位密码",@"请输入你常用的邮箱"];
    CGSize TextSize1 = [@"账       号:" sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]}];
    CGSize TextSize2 = [@"输入邮箱:" sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]}];
    for (int i = 0; i < 3; i++) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(btn.frame) -  20, CGRectGetMaxY(btn.frame) + 20 + 20*i + 10*i, TextSize2.width, 30)];
        label.font = [UIFont systemFontOfSize:17];
        label.text = titleArr[i];
        UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(label.frame) + 5, CGRectGetMinY(label.frame), CGRectGetWidth(self.view.frame) - CGRectGetMaxX(label.frame) - 5 - 20, 30)];
        textField.font = [UIFont systemFontOfSize:15];
        textField.delegate = self;
        textField.tag = 2000 + i;
        textField.secureTextEntry = YES;
        textField.placeholder = placeholderArr[i];
        
        UIView *lane = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMinX(textField.frame), CGRectGetMaxY(textField.frame) - 5, CGRectGetWidth(textField.frame), 1)];
        lane.backgroundColor = [UIColor blackColor];
        if (i == 0) {
            label.frame = CGRectMake(CGRectGetMinX(btn.frame) - 20, CGRectGetMaxY(btn.frame) + 20, TextSize1.width, 30);
            textField.frame = CGRectMake(CGRectGetMaxX(label.frame)+5, CGRectGetMinY(label.frame), CGRectGetWidth(self.view.frame) - CGRectGetMaxX(label.frame) - 5 - 20, 30);
            textField.placeholder = @"账号3-10位的字母和数字组成";
            lane.frame = CGRectMake(CGRectGetMinX(textField.frame), CGRectGetMaxY(textField.frame) - 5, CGRectGetWidth(textField.frame), 1);
            textField.secureTextEntry = NO;
        }
        [headView addSubview:label];
        [headView addSubview:textField];
        [headView addSubview:lane];
    }

    
    UIButton *nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    nextBtn.tag = 1000;
    nextBtn.frame = CGRectMake(CGRectGetMinX(btn.frame) - 20, CGRectGetMaxY(btn.frame) + 40 + 30*3, CGRectGetWidth(textView.frame), 40);
    nextBtn.selected = NO;
    [nextBtn setBackgroundColor:[UIColor lightGrayColor]];
    [nextBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
    [nextBtn setTitle:@"下一步" forState:UIControlStateSelected];
    [nextBtn addTarget:self action:@selector(NextBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:nextBtn];
    
    return headView;
}

//同意按钮响应方法
-(void)selectBtnAction:(UIButton *)sender {
    UIButton *btn = (UIButton *)[self.view viewWithTag:1000];
    if (sender.selected) {
        sender.selected = NO;
        btn.selected = NO;
        btn.backgroundColor = [UIColor lightGrayColor];
    }else {
        sender.selected = YES;
        btn.selected = YES;
        btn.backgroundColor = [UIColor greenColor];
    }
}

//下一步按钮响应方法
-(void)NextBtnAction:(UIButton *)sender {
    if (!sender.selected) {
        return;
    }else {
        /*
        UITextField *TF_2 = (UITextField *)[self.view viewWithTag:2001];
        UITextField *TF_3 = (UITextField *)[self.view viewWithTag:2002];
        if (TF_2.text.length <= 0 || TF_3.text.length <= 0) {
            UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"注意" message:@"请输入密码" delegate:nil cancelButtonTitle:@"退出" otherButtonTitles:nil, nil];
            [alert show];
            return;
        }
        if (![TF_2.text isEqualToString:TF_3.text]) {
            UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"注意" message:@"两次输入不一致" delegate:nil cancelButtonTitle:@"退出" otherButtonTitles:nil, nil];
            [alert show];
            return;
        }
        //检测用户输入第一位必须大写,第二位必须小写,数字和字母的组合，并且最大长度不超过18，最小长度不小于6
        NSString *text1 = TF_2.text;
        //        NSString * regularExpression=@"[A-Z]{1,}[a-z]{1,}[0-9a-zA-Z]{5,17}$";
        //密码判断,包含大小写字母数字
        //^ 匹配一行的开头位置
        //(?![0-9]+$) 预测该位置后面不全是数字
        //(?![a-zA-Z]+$) 预测该位置后面不全是字母
        //(?![a-z0-9]+$) 预测该位置后面不全是小写字母和数字
        //(?![A-Z0-9]+$) 预测该位置后面不全是大写字母和数字
        //[a-zA-Z0-9]{6,18}  由8-16位数字或这字母组成
        //$ 匹配行尾位置
        NSString * regularExpression = @"^(?![0-9]+$)(?![a-zA-Z]+$)(?![a-z0-9]+$)(?![A-Z0-9]+$)[a-zA-Z0-9]{6,18}";
        NSPredicate *pre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regularExpression];
        BOOL flag = [pre evaluateWithObject:text1];
        if (!flag) {
            UIAlertView * alert=[[UIAlertView alloc]initWithTitle:@"注意" message:@"输入格式有误!" delegate:nil cancelButtonTitle:@"退出" otherButtonTitles:nil, nil];
            [alert show];
            return;
        }
        
        UITextField *TF_1 = (UITextField *)[self.view viewWithTag:2000];
        BOOL Emailsuccess = [self validateEmail:TF_1.text];
        if (!Emailsuccess) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示:" message:@"邮箱输入有误!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alert show];
            return;
        } else {
            NSString *str = TF_1.text;
            NSString *url = [NSString stringWithFormat:@"MobilePort/Index/check_user_email.html?email=%@",str];
            [[HTTPGlobals shareHTTPGlobal] GetHTTPRequest:url parameters:nil finish:^(BOOL seccess, NSString *error, id obj) {
                if (seccess) {
                    DLog(@"obj = %@",obj[@"msg"]);
                    NSString *lenght = obj[@"msg"];
                    if (lenght.length > 0) {
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示:" message:@"邮箱已注册,请重新输入邮箱" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                        [alert show];
                        return;
                    }else {
                        //注册
                        [self.HUD show:YES];
                        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                        [dic setObject:TF_1.text forKey:@"email"];
                        [dic setObject:TF_2.text forKey:@"password1"];
                        [dic setObject:TF_3.text forKey:@"password2"];
                        NSString *url = @"MobilePort/Index/regist.html";
                        [[HTTPGlobals shareHTTPGlobal] PostHTTPRequest:url parameters:dic finish:^(BOOL seccess, NSString *error, id obj) {
                            [self.HUD hide:YES];
#warning 这里有log输出
                            DLog(@"obj = ______%@",obj);
                            DLog(@"info = %@",obj[@"info"]);
                            DLog(@"status = %@",obj[@"status"]);
                            DLog(@"url = %@",obj[@"url"]);
                            if (seccess) {
                                [self pushViewController:[YunPlatformSet new]];
                            }
                            else {
         
                                [self.HUD hide:YES];
                                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示:" message:@"注册失败，请检查网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                                [alert show];
                            }
                        }];
                        
                    }
                }
            }];
        }
         */
        [self pushViewController:[YunPlatformSet new]];
    }
         
}
//检测邮箱是否正确
-(BOOL)validateEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

-(void)menu {
    
}

#pragma mark -
#pragma mark --textFieldDelegate--
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    [UIView animateWithDuration:0.3 animations:^{
        _tableView.frame = CGRectMake(0, -120, _tableView.frame.size.width, _tableView.frame.size.height);
    } completion:^(BOOL finished) {
        
    }];
    return YES;
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    [UIView animateWithDuration:0.3 animations:^{
        _tableView.frame = CGRectMake(0, 0, _tableView.frame.size.width, _tableView.frame.size.height);
    } completion:^(BOOL finished) {
        
    }];
    return YES;
}

#pragma mark -
#pragma mark --tableviewDelegate--
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 0;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *indentifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:indentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifier];
    }
    
    return cell;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headView = [self buildMainView];
    return headView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    UIView *headView = [self tableView:tableView viewForHeaderInSection:section];
    
    return CGRectGetHeight(headView.frame);
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    UITextField *TF = (UITextField *)[self.view viewWithTag:2000];
    UITextField *TF1 = (UITextField *)[self.view viewWithTag:2001];
    UITextField *TF2 = (UITextField *)[self.view viewWithTag:2002];
    [TF1 resignFirstResponder];
    [TF resignFirstResponder];
    [TF2 resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
